import socket
import sys
import threading
from utils import decode_data

def handle_new_client(tcp_client: socket.socket, tcp_client_addr: tuple):
    thread_name = threading.current_thread().name
    tcp_client.send(f"欢迎光临:{thread_name}!".encode())
    
    while True:
        recv_data = tcp_client.recv(1024)
        if recv_data:
            msg = decode_data(recv_data)
            print(f"收到来自{tcp_client_addr}的消息:{msg}")
            tcp_client.send("消息已收到".encode())
        else:
            print("客户端已经断开:", tcp_client_addr)
            break
        
    tcp_client.close()
    
def main():
    args = sys.argv[1: ]
    
    #建立TCP服务器
    tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    port = 8888
    
    tcp_server.bind(("", port))
    tcp_server.listen(128)
    
    index = 0
    
    print("服务器已经启动，端口{}".format(port))
    while True:
        tcp_client, tcp_client_addr = tcp_server.accept()
        print(f"有新的客户端{tcp_client_addr}接入")
        t1 = threading.Thread(
            target=handle_new_client,
            name=f"威尼斯水城VIP{index}",
            args=(tcp_client, tcp_client_addr),
            daemon= True)
        t1.start()
        index += 1
        
    tcp_server.close()
    
if __name__ == '__main__':
    main()
